//
//  PVDDetailView.swift
//  GreenDeal
//
//  Created by Moennig Q on 26/12/2022.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
class JobDetailView: JobDetailBaseView {
    fileprivate lazy var disposeBag = DisposeBag()
    let scrollView = DIYScrollView()
    let contentView = UIView()
    let topView = JobDetailTopView()
    let pickupAddressView = JobDetailPickupAddressView()
    let jobSiteInstructionForInstallerView = JobDetailJobSiteInstructionView()
    let systemInfoLabel = ContentLabel(R.font.interRegular(size: 12),hexStr: "#292D3299")
    let systemInfoView = JobDetailSystemInfoView()
    let checklistTableView = InstallationChecklistTableView()
    //flush reupload
    let supportFunctionView = JobDetailSupportFunctionView()
    //phone and email
    let supportView = JobDetailSupportView()
    let bottomView = JobDetailBottomView()
    let finishJobBtn = OperationButton(R.string.localizable.finishJob())
    let reopenJobBtn = OperationButton(R.string.localizable.reopenJob())
    //加载失败的额视图
    lazy var loadFaildView = DatalLoadFaildView()
    var checklistTableViewHeightConstraint: Constraint?
    //是否显示底部三个导航按钮，
    var showBottomViewFlag: Bool = false
    override func setUpView() {
        //加载失败的试图
        loadFaildView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(loadFaildView)
        loadFaildView.snp.makeConstraints { make in
            make.top.equalTo(backToPreBtn.snp.bottom).offset(16)
            make.bottom.left.right.equalToSuperview()
        }
        //bottom view
        self.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        //
        scrollView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(backToPreBtn.snp.bottom).offset(16)
            make.left.right.equalTo(self)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        contentView.backgroundColor = UIColor(hexStr: Constant.TransparentColorHexStr)
        scrollView.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //*******job top view
        contentView.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(0)
        }
        contentView.addSubview(pickupAddressView)
        pickupAddressView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //Job site instruction for installer
        contentView.addSubview(jobSiteInstructionForInstallerView)
        jobSiteInstructionForInstallerView.snp.makeConstraints { make in
            make.top.equalTo(pickupAddressView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //*******system info view
        systemInfoLabel.text = "SYSTEM INFORMATION"
        contentView.addSubview(systemInfoLabel)
        systemInfoLabel.snp.makeConstraints { make in
            make.top.equalTo(jobSiteInstructionForInstallerView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(24)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //
        contentView.addSubview(systemInfoView)
        systemInfoView.snp.makeConstraints { make in
            make.top.equalTo(systemInfoLabel.snp.bottom).offset(Constant.AllOutMargin / 2)
            make.left.right.equalTo(topView)
            make.height.greaterThanOrEqualTo(0)
        }
        //checklist view
        contentView.addSubview(checklistTableView)
        checklistTableView.snp.makeConstraints { make in
            make.top.equalTo(systemInfoView.snp.bottom)
            make.left.right.equalToSuperview()
            self.checklistTableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
        }
        //suppor function
        let supportFuncLabel = ContentLabel(R.font.interRegular(size: 12),hexStr: "#292D3299")
        supportFuncLabel.text = "SUPPORT FUNCTIONS"
        contentView.addSubview(supportFuncLabel)
        supportFuncLabel.snp.makeConstraints { make in
            make.top.equalTo(checklistTableView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(24)
            make.width.height.greaterThanOrEqualTo(0)
        }
        contentView.addSubview(supportFunctionView)
        supportFunctionView.snp.makeConstraints { make in
            make.top.equalTo(supportFuncLabel.snp.bottom).offset(8)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //supporview
        let supportLabel = ContentLabel(R.font.interRegular(size: 12),hexStr: "#292D3299")
        supportLabel.text = "SUPPORT"
        contentView.addSubview(supportLabel)
        supportLabel.snp.makeConstraints { make in
            make.top.equalTo(supportFunctionView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(24)
            make.width.height.greaterThanOrEqualTo(0)
        }
        contentView.addSubview(supportView)
        supportView.snp.makeConstraints { make in
            make.top.equalTo(supportLabel.snp.bottom).offset(9)
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(0)
        }
        //Finish job
        contentView.addSubview(finishJobBtn)
        finishJobBtn.snp.makeConstraints { make in
            make.top.equalTo(supportView.snp.bottom).offset(24)
            make.left.right.equalTo(supportView)
            make.height.equalTo(0)
            make.bottom.equalTo(-10)
        }
        contentView.bringSubviewToFront(self.bottomView)
        //监听说明有没有，没有不显示，有就显示
        JobDetailModelHelper.shared.installer_job_site_instruction.subscribe { [weak self] (data) in
            guard let strongSelf = self else {return }
            strongSelf.dealJobSiteInstructionView()
        }.disposed(by: self.disposeBag)
        //监听pick up required是否为true。true就显示，false不显示
        JobDetailModelHelper.shared.pick_up_required.subscribe { [weak self] (data) in
            guard let strongSelf = self else {return }
            strongSelf.dealPickupAddressView()
        }.disposed(by: self.disposeBag)
        //绑定checklisttableview的g
        checklistTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.checklistTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //checklist 必填项的已完成数量及需需完成数量, 本地数据不统计
        JobDetailModelHelper.shared.pvd_checklists.subscribe { [weak self] (list) in
            guard let strongSelf = self else {return }
            //*******checklist数量
            //0.所有系统checklist的必填项，包括NOC（type也是Image）和date of commissioning
            let requirdList = list.filter({
                if $0.is_required == "true" && ($0.type == ChecklistType.Bool.rawValue || $0.type == ChecklistType.Text.rawValue || $0.type == ChecklistType.Image.rawValue || $0.type == ChecklistType.PanelInstalled.rawValue) {
                    return true
                }else{
                    return false
                }})
            //1.统计image，text，bool，的完成数量
            let checklistDoneList = requirdList.filter({ checkModel in
                if checkModel.type == ChecklistType.Text.rawValue || checkModel.type == ChecklistType.Bool.rawValue{
                    if checkModel.dbId == 0 {//已上传的数据
                        if checkModel.answered_at != ""{
                            return true
                        }else{
                            return false
                        }
                    }else{//本地数据不统计
                        return false
                    }
                    
                }else if checkModel.type == ChecklistType.Image.rawValue{
                    let serverImagesCnt = checkModel.images.filter({$0.oper_type == ""}).count//已经上传的image
                    if  checkModel.minimum_quantity > 0{
                        if serverImagesCnt >= checkModel.minimum_quantity {
                            return true
                        }
                    }else{
                        if serverImagesCnt > 0 {
                            return true
                        }
                    }
                }else if checkModel.type == ChecklistType.PanelInstalled.rawValue{
                    if JobDetailModelHelper.shared.jobDetailModel.spv_installed {
                        return true
                    }else{
                        return false
                    }
                }
                return false
            })
            strongSelf.bottomView.checklistBtn.setData(.checklist, finishCnt: checklistDoneList.count, plantCnt: requirdList.count)
            //*******signatures数量
            let signaturesList: [PVDChecklistModel] = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.filter({$0.section == .signatures && $0.type != ChecklistType.headerWithImage.rawValue})
            let signaturesPlanCnt = signaturesList.count
            //不统计本地数据
            var finishSignaturePlanCnt = 0
            if JobDetailModelHelper.shared.jobDetailModel.is_new_stc_form{//新协议
                if JobDetailModelHelper.shared.jobDetailModel.isInstallerAndDesigner {//installer & designer
                    if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_at != "" && JobDetailModelHelper.shared.jobDetailModel.signatures.designer_signed_at != "" {
                        finishSignaturePlanCnt += 1
                    }
                }else{
                    //installer
                    if JobDetailModelHelper.shared.jobDetailModel.signatures.installer_signed_at != "" {
                        finishSignaturePlanCnt += 1
                    }
                    //designer
                    if JobDetailModelHelper.shared.jobDetailModel.signatures.designer_signed_at != "" {
                        finishSignaturePlanCnt += 1
                    }
                }
                //owner
                if JobDetailModelHelper.shared.jobDetailModel.signatures.owner_signed_at != ""  {
                    finishSignaturePlanCnt += 1
                }
            }else{//老协议
                finishSignaturePlanCnt = signaturesList.filter({ $0.answered_at != "" && $0.localDataflag == false}).count
            }
            strongSelf.bottomView.signatureBtn.setData(.signature, finishCnt: finishSignaturePlanCnt, plantCnt: signaturesPlanCnt)
            //*******panel and inverter数量
            let panelPlanCnt = JobDetailModelHelper.shared.jobDetailModel.system_detail.panel_plant_count
            let inverterPlanCnt = JobDetailModelHelper.shared.jobDetailModel.system_detail.inverter_plant_count
            //不统计本地数据
            let panelScanedCnt = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.filter({$0.operType == ""}).count
            let inverterScanedCnt = JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers.filter({$0.operType == ""}).count
            //
            //
            let panelFinishCnt = (panelScanedCnt > panelPlanCnt ? panelPlanCnt : panelScanedCnt)
            let inverterFinishCnt = (inverterScanedCnt > inverterPlanCnt ? inverterPlanCnt : inverterScanedCnt)
            strongSelf.bottomView.barcodeBtn.setData(.barcode, finishCnt: panelFinishCnt + inverterFinishCnt, plantCnt: panelPlanCnt + inverterPlanCnt)
        }.disposed(by: self.disposeBag)
        //job_ status
        JobDetailModelHelper.shared.job_status.subscribe(onNext: { [weak self] (status) in
            guard let strongSelf = self else {return}
            strongSelf.showEditIconByJobStatus(status)
        }).disposed(by: self.disposeBag)

        //默认隐藏detail view, failed view
        self.scrollView.isHidden = true
        self.loadFaildView.isHidden = true
        self.scrollView.delegate = self
    }
    //MARK: - 处理是否显示pick up address，job site instruction
    private func dealPickupAddressView(){
        pickupAddressView.isHidden = !JobDetailModelHelper.shared.jobDetailModel.pick_up_required
        if  JobDetailModelHelper.shared.jobDetailModel.pick_up_required {//显示pick up address
            pickupAddressView.setData(JobDetailModelHelper.shared.jobDetailModel.delivery_address.map_full_address, refNo: JobDetailModelHelper.shared.jobDetailModel.pick_up_reference)
            pickupAddressView.snp.remakeConstraints { make in
                make.top.equalTo(topView.snp.bottom)
                make.left.right.equalToSuperview()
                make.height.greaterThanOrEqualTo(0)
            }
        }else{//不显示pick up address
            pickupAddressView.snp.remakeConstraints { make in
                make.bottom.equalTo(topView)
                make.left.right.equalToSuperview()
                make.height.equalTo(0)
            }
        }
    }
    private func dealJobSiteInstructionView(){
        jobSiteInstructionForInstallerView.isHidden = (JobDetailModelHelper.shared.jobDetailModel.installer_job_site_instruction == "" ? true : false)
        if  JobDetailModelHelper.shared.jobDetailModel.installer_job_site_instruction != "" {//显示job site instructions
            //Job site instruction for installer
            jobSiteInstructionForInstallerView.snp.remakeConstraints { make in
                make.top.equalTo(pickupAddressView.snp.bottom)
                make.left.right.equalToSuperview()
                make.height.greaterThanOrEqualTo(0)
            }
        }else{//不显示job site instructions
            jobSiteInstructionForInstallerView.snp.remakeConstraints { make in
                make.bottom.equalTo(pickupAddressView)
                make.left.right.equalToSuperview()
                make.height.equalTo(0)
            }
        }
    }
    //MARK: - 根据job状态，变化UI
    fileprivate func showEditIconByJobStatus(_ status: String){
        self.topView.editAddressBtn.isHidden = !JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag
        self.systemInfoView.checkIfShowMoreImageView()
        self.showBottomViewByJobStatus(JobDetailModelHelper.shared.jobDetailModel.job_status)
    }
    func showDetailView(){
        self.showEditIconByJobStatus(JobDetailModelHelper.shared.jobDetailModel.job_status)
        //只有installer才能编辑job detail
        self.scrollView.isHidden = false
        self.bottomView.isHidden = false
        self.loadFaildView.isHidden = true
        //立即刷新子对象布局，用于加载数据完成后，跳转到相应的位置
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    func showFaildView(){
        self.scrollView.isHidden = true
        self.bottomView.isHidden = true
        self.loadFaildView.isHidden = false
    }
    //
    private func showBottomViewByJobStatus(_ status: String){
        self.showBottomViewFlag = false
        if status == PVDJobStatusValue.installed.rawValue{//installed, 显示reopen job按钮隐藏bottom view
            //finish job不显示
            finishJobBtn.isHidden = true
            finishJobBtn.snp.remakeConstraints { make in
                make.top.equalTo(supportView.snp.bottom)
                make.left.right.equalTo(supportView)
                make.height.equalTo(0)
                make.bottom.equalTo(-10)
            }
            //隐藏bottom view
            if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {//installer才能reopen job
                //bottomview的高度，因为reopen在bottom的中间
                //显示BottomView
                self.showBottomViewFlag = true
                bottomView.snp.remakeConstraints { make in
                    make.bottom.left.right.equalToSuperview()
                    make.height.greaterThanOrEqualTo(0)
                }
                //1.增加repopen
                if self.reopenJobBtn.superview == nil{
                    self.addSubview(reopenJobBtn)
                }
                reopenJobBtn.snp.makeConstraints { make in
                    make.top.equalTo(bottomView).offset(15)//15和bottom view中的按钮的top是一致的
                    make.left.equalTo(16)
                    make.right.equalTo(-16)
                    make.height.equalTo(OperationButton.height)
                }
            }else{//非installer不显示能=reopen job
                if let _ = self.reopenJobBtn.superview{
                    reopenJobBtn.removeFromSuperview()
                }
                //bottom view也隐藏
                bottomView.snp.remakeConstraints { make in
                    make.bottom.left.right.equalToSuperview()
                    make.height.equalTo(0)
                }
            }
        }else{
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{//显示finish job
                finishJobBtn.isHidden = false
                finishJobBtn.snp.remakeConstraints { make in
                    make.top.equalTo(supportView.snp.bottom).offset(24)
                    make.left.right.equalTo(supportView)
                    make.height.equalTo(OperationButton.height)
                    make.bottom.equalTo(-10)
                }
            }else{
                finishJobBtn.isHidden = true
                finishJobBtn.snp.remakeConstraints { make in
                    make.top.equalTo(supportView.snp.bottom)
                    make.left.right.equalTo(supportView)
                    make.height.equalTo(0)
                    make.bottom.equalTo(-10)
                }
            }
            finishJobBtn.isHidden = !JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag
            
            //显示bottom view
            self.showBottomViewFlag = true
            bottomView.snp.remakeConstraints { make in
                make.bottom.left.right.equalToSuperview()
                make.height.greaterThanOrEqualTo(0)
            }
            //不显示reopen job
            if let _ = self.reopenJobBtn.superview{
                reopenJobBtn.removeFromSuperview()
            }
        }
    }
}
extension JobDetailView: UIScrollViewDelegate {
    //MARK: - 开始拖动时隐藏
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if self.showBottomViewFlag {//Bottom View显示的时候才做处理
            UIView.animate(withDuration: 0.5) {
                self.bottomView.snp.remakeConstraints { make in
                    make.bottom.left.right.equalToSuperview()
                    make.height.equalTo(0)
                }
                self.layoutIfNeeded()
            }
        }
    }
    //MARK: - 结束拖动时显示
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if self.showBottomViewFlag {//Bottom View显示的时候才做处理
            UIView.animate(withDuration: 0.5) {
                self.bottomView.snp.remakeConstraints { make in
                    make.bottom.left.right.equalToSuperview()
                    make.height.greaterThanOrEqualTo(0)
                }
                self.layoutIfNeeded()
            }
        }
        
    }
}
